<script setup>

import Header from "@/components/Header.vue";
import BackTop from "@/components/BackTop.vue";
import {Upload} from "@element-plus/icons-vue";
import Footer from "@/components/Footer.vue";
</script>
·
<template>
  <header>
    <Header></Header>
  </header>
  <BackTop></BackTop>
  <main>
    <div class="page-container">
      <el-card>
        <el-icon>
          <Upload/>
        </el-icon>&nbsp;
        <b>视频上传 UploadVideo</b>
        <el-divider></el-divider>
        <el-form :model="form" ref="form" :rules="rule">
          <el-form-item size="large" label="视频标题：" prop="title">
            <el-input v-model="form.title" placeholder="请输入你的视频标题"/>
          </el-form-item>
          <el-form-item size="large" label="视频分类：" prop="category">
            <div v-for="(tag, index) in form.category" :key="index">
              <el-tag closable color="#3baeea" class="tag-label" style="border: none" effect="dark"
                      :disable-transitions="false"
                      @close="removeTag(tag)">{{ tag }}
              </el-tag>
            </div>
            <el-input
                v-model="newTag"
                placeholder="输入分类并回车添加"
                @keyup.enter.native="addTag"
                clearable
            ></el-input>
          </el-form-item>
          <el-form-item size="large" label="视频封面：" prop="cover">
            <el-input v-model="form.cover" placeholder="请上传你的视频封面"/>
          </el-form-item>
          <el-form-item size="large" label="视频描述：" prop="description">
            <el-input v-model="form.description" type="textarea" placeholder="请描述一下所上传的视频"/>
          </el-form-item>
          <el-form-item label="上传视频：" prop="fileList">
            <el-upload
                ref="uploads"
                v-model="form.fileList"
                class="upload-demo"
                action="http://localhost:9000/upload/uploadVideo"
                :auto-upload="false"
                :on-success="handleSuccess"
                :before-upload="beforeUpload"
                :on-change="pushFile"
                :on-remove="removeFile"
                :limit="1"
                :on-exceed="handleExceed"
                :file-list="fileList"
                accept="video/*"
                drag
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将视频文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只能上传视频文件，且不超过 500MB</div>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button class="submit-button" type="primary" size="large" @click="submitForm('form')"><b>上传视频</b>
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </main>
  <footer>
    <Footer/>
  </footer>
</template>

<script>
import axios from "axios";
import {getToken} from "@/utils/auth";

export default {
  data() {
    return {
      form: {
        title: '',
        description: '',
        cover: '',
        category: [],
        fileList: [],
      },
      fileList: [],
      newTag: "",
      rule: {
        title: [
          {required: true, message: "请输入视频标题！", trigger: "blur"},
          {min: 3, message: "视频标题不得少于3个字符！", trigger: "blur"}
        ],
        cover: [
          {required: true, message: "请上传视频封面！", trigger: "blur"},
        ],
        category: [
          {required: true, message: "请添加视频分类标签！", trigger: "blur"},
        ],
        description: [
          {required: true, message: "请描述你上传的视频内容！", trigger: "blur"},
        ],
        fileList: [
          {required: true, message: "请上传视频源文件！", trigger: "change"}
        ]
      }
    };
  },
  methods: {
    beforeUpload(file) {
      const isVideo = file.type.indexOf('video/') === 0;
      const isLt500M = file.size / 1024 / 1024 < 500;
      if (!isVideo) {
        this.$message.error('上传文件只能是视频格式!');
      }
      if (!isLt500M) {
        this.$message.error('上传视频大小不能超过 500MB!');
      }
      return isVideo && isLt500M;
    },
    handleSuccess(response, file, fileList) {
      this.$message({
        message: '上传成功',
        type: 'success',
      });
      // 处理上传成功后的逻辑，比如更新 fileList 或表单数据等
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    pushFile(file) {
      this.fileList.push(file);
      this.form.fileList = this.fileList;
      // 防止用户打开了文件选择框之后不选择文件而出现效验失败
      if(this.form.fileList){
        this.$refs.form.clearValidate('fileList');
      }
    },
    removeFile(){
      //移除上传文件
      this.fileList.pop();
      this.form.fileList = this.fileList;
      this.$refs.form.validateField('fileList');
    },
    addTag() {
      if (this.newTag.trim()) {
        const new_tag = this.newTag.trim();
        if (this.form.category.includes(new_tag)) {
          this.$message.warning("已存在相同标签，请勿重复添加！");
        } else if (this.form.category.length >= 5) {
          this.$message.warning("单个视频最多只能5个标签！");
        } else {
          this.form.category.push(this.newTag.trim());
          this.newTag = '';
        }
      }
    },
    removeTag(tag) {
      this.form.category.splice(this.form.category.indexOf(tag), 1);
    },
    submitForm(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          const headers = {
            // 添加请求头
            headers: {
              'Content-Type': 'multipart/form-data',
              'token': getToken()
            }
          };
          const formData = new FormData();
          formData.append('title', this.form.title);
          formData.append('category', this.form.category.toString());
          formData.append('description', this.form.description);
          formData.append('cover', this.form.cover);
          formData.append('file', this.fileList[0].raw);
          axios.post("http://localhost:9000/upload/uploadVideo", formData, headers).then(
              res => {
                if (res.status === 200) {
                  console.log(res);
                  this.$message.success("视频已上传成功！");
                }
              }
          ).catch(error => {
            if (error.response.status === 300) {
              this.$message.error(error.response.data);
            } else {
              this.$message.error("上传失败，请重试！");
            }
          })
        } else {
          this.$message.warning("格式不正确！")
          return false;
        }
      });
    },
  },
};
</script>

<style scoped>
main {
  margin-bottom: 10rem;
}

.upload-demo {
  width: 100%;
  line-height: 60px;
  text-align: center;
  border-radius: 6px;
  cursor: pointer;
}

.upload-demo i {
  font-size: 28px;
  color: #999;
}

.el-upload__text {
  color: #666;
  font-size: 14px;
  text-align: center;
}

.el-upload__tip {
  color: #999;
  font-size: 12px;
  text-align: center;
}

.page-container {
  width: 80%;
  min-height: 120vh;
  margin: auto;
  position: relative;
  top: 50px;
}

.submit-button {
  position: relative;
  width: 40%;
  margin-left: 30%;
}

.tag-label {
  margin-right: 5px;
  margin-bottom: 5px;
}

</style>
